import type { DescInstance, DescriptionProps, UseDescReturnType } from "./typing";
import { isProdMode } from "@/utils/env";
import { useEffect, useRef } from "react";

export function useDescription(props?: Partial<DescriptionProps>): UseDescReturnType {
	const desc = useRef<Nullable<DescInstance>>(null);
	const loaded = useRef(false);

	useEffect(() => {
		return () => {
			desc.current = null;
			loaded.current = false;
		};
	}, []);

	function register(instance: DescInstance) {
		if (loaded && isProdMode() && instance == desc.current) return;
		desc.current = instance;
		props && instance.setDescProps(props);
		loaded.current = true;
	}

	const methods: DescInstance = {
		setDescProps: (descProps: Partial<DescriptionProps>): void => {
			desc.current?.setDescProps(descProps);
		}
	};
	return [register, methods];
}
